package org.wk.core.common.tool;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author df.wu
 */
public class ExcelUtils {

    /**
     * 导出Excel
     * @param sheetName sheet名称
     * @param rowName 标题
     * @param dataList 内容
     * @return
     */
    public static HSSFWorkbook getHSSFWorkbook(String sheetName, String []rowName, List<Object[]> dataList){
        return getHSSFWorkbook(sheetName,rowName,dataList,null);
    }

    /**
     * 导出Excel
     * @param title 标题
     * @param rowName 列名称
     * @param dataList 内容
     * @param workbook HSSFWorkbook对象
     * @return
     */
    public static HSSFWorkbook getHSSFWorkbook(String title, String [] rowName, List<Object[]> dataList, HSSFWorkbook workbook ){

        // 第一步，创建一个HSSFWorkbook，对应一个Excel文件
        if(workbook == null){
            workbook = new HSSFWorkbook();
        }

        // 第二步，在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = workbook.createSheet(title);

        // 第三步，在sheet中添加表格标题行
        HSSFRow rowm = sheet.createRow(0);
        HSSFCell cellTiltle = rowm.createCell(0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        //sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面  - 可扩展】
        //获取列头样式对象
        HSSFCellStyle columnTopStyle = getColumnTopStyle(workbook);
        //单元格样式对象
        HSSFCellStyle style = getStyle(workbook);

        sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1)));
        cellTiltle.setCellStyle(columnTopStyle);
        cellTiltle.setCellValue(title);

        // 定义所需列数
        int columnNum = rowName.length;
        // 在索引2的位置创建行(最顶端的行开始的第二行)
        HSSFRow rowRowName = sheet.createRow(2);

        // 将列头设置到sheet的单元格中
        for(int n=0;n<columnNum;n++){
            //创建列头对应个数的单元格
            HSSFCell  cellRowName = rowRowName.createCell(n);
            //设置列头单元格的数据类型
            cellRowName.setCellType(CellType.STRING);
            HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
            //设置列头单元格的值
            cellRowName.setCellValue(text);
            //设置列头单元格样式
            cellRowName.setCellStyle(columnTopStyle);
        }
        //将查询出的数据设置到sheet对应的单元格中
        for(int i=0;i<dataList.size();i++){
            //遍历每个对象
            Object[] obj = dataList.get(i);
            //创建所需的行数
            HSSFRow row = sheet.createRow(i+3);

            for(int j=0; j<obj.length; j++){
                //设置单元格的数据类型
                HSSFCell  cell = null;
                if(j == 0){
                    cell = row.createCell(j,CellType.NUMERIC);
                    cell.setCellValue(i+1);
                }else{
                    cell = row.createCell(j,CellType.STRING);
                    if(!"".equals(obj[j]) && obj[j] != null){
                        //设置单元格的值
                        cell.setCellValue(obj[j].toString());
                    }
                }
                //设置单元格样式
                cell.setCellStyle(style);
            }
        }
        //让列宽随着导出的列长自动适应
        for (int colNum = 0; colNum < columnNum; colNum++) {
            int columnWidth = sheet.getColumnWidth(colNum) / 256;
            for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                HSSFRow currentRow;
                //当前行未被使用过
                if (sheet.getRow(rowNum) == null) {
                    currentRow = sheet.createRow(rowNum);
                } else {
                    currentRow = sheet.getRow(rowNum);
                }
                if (currentRow.getCell(colNum) != null) {
                    HSSFCell currentCell = currentRow.getCell(colNum);
                    if (CellType.STRING.equals(currentCell.getCellStyle())) {
                        int length = currentCell.getStringCellValue().getBytes().length*2*256;
                        if (columnWidth < length) {
                            columnWidth = length;
                        }
                    }
                }
            }
            if(colNum == 0){
                sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
            }else{
                sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
            }
        }



        return workbook;
    }
    /**
     * 列头单元格样式
     */
    public static HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {

        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short)11);
        //字体加粗
        font.setBold(true);
        //设置字体名字
        font.setFontName("Courier New");
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(BorderStyle.THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //设置左边框;
        style.setBorderLeft(BorderStyle.THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //设置右边框;
        style.setBorderRight(BorderStyle.THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //设置顶边框;
        style.setBorderTop(BorderStyle.THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }

    /**
     * 列数据信息单元格样式
     */
    public static HSSFCellStyle getStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        //font.setFontHeightInPoints((short)10);
        //字体加粗
        //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //设置字体名字
        font.setFontName("Courier New");
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(BorderStyle.THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //设置左边框;
        style.setBorderLeft(BorderStyle.THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //设置右边框;
        style.setBorderRight(BorderStyle.THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //设置顶边框;
        style.setBorderTop(BorderStyle.THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        return style;

    }
    public static void main(String[] args) {
        String title = "送货单";
        String[] rowsName = new String[]{"序号","货物运输批次号","提运单号","状态","录入人","录入时间"};
        List<Object[]>  dataList = new ArrayList<Object[]>();
        Object[] objs = null;

        List<Map<String,String>> data = new ArrayList<>();
        for (int i=0;i<10;i++) {
            Map<String,String> map = new HashMap<>();
            map.put("tranNo",String.valueOf(i));
            map.put("billNo",String.valueOf(i));
            map.put("tiyunNo",String.valueOf(i));
            map.put("flag",String.valueOf(i));
            map.put("loginName",String.valueOf(i));
            map.put("modiDate",String.valueOf(i));
            data.add(map);
        }

        for (int i = 0; i < data.size(); i++) {
            Map<String,String> man = data.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i;
            objs[1] = man.get("tranNo");
            objs[2] = man.get("tranNo");
            objs[3] = man.get("tranNo");
            objs[4] = man.get("tranNo");
            objs[5] = man.get("tranNo");
            dataList.add(objs);
        }

        HSSFWorkbook workbook = getHSSFWorkbook(title,rowsName,dataList);

        File file = new File("d:/xxx.xls");
        try {
            workbook.write(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}
